package m202311.d21;

/**
 * @author haocongshun
 * @date 2023/11/21 18:26:14
 */

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 68. 文本左右对齐
 */
public class Q68 {

    public static void main(String[] args) {
        List<String> list = new Q68().fullJustify(new String[]{"What", "must", "be", "acknowledgment", "shall", "be"}, 16);
        System.out.println();
    }

    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> lines = new LinkedList<>();
        int start = 0;
        int[] end = getEnd(words, maxWidth, start);
        while (end[0] != -1) {
            StringBuilder sb = new StringBuilder();
            if (end[0] == words.length) {
                for (int i = start; i < end[0]; i++) {
                    sb.append(words[i]);
                    if (sb.length() < maxWidth) {
                        sb.append(" ");
                    }
                }
                if (sb.length() < maxWidth) {
                    sb.append(space(maxWidth - sb.length()));
                }

            }else {
                String[] space = space(maxWidth - end[1], end[0] - start);
                int s = 0;
                for (int i = start; i < end[0]; i++, s++) {
                    sb.append(words[i]);
                    if (s < space.length) {
                        sb.append(space[s]);
                    }
                }
            }
            lines.add(sb.toString());
            start = end[0];
            end = getEnd(words, maxWidth, start);
        }
        return lines;
    }

    public int[] getEnd(String[] words, int maxWidth, int start) {
        int count = 0;
        if (start >= words.length) {
            return new int[]{-1, 0};
        }
        for (int i = start; i < words.length; i++) {
            count = count + words[i].length();
            if ((count + (i - start)) > maxWidth) {
                return new int[]{i, count - words[i].length()};
            }
        }
        return new int[]{words.length, count};
    }

    public String[] space(int count, int number) {
        if (number - 1 == 0) {
            return new String[]{space(count)};
        }
        String[] sbs = new String[number - 1];
        int eve = count / (number - 1);
        int offset = count % (number - 1);
        for (int i = 0; i < sbs.length; i++) {
            sbs[i] = space(eve);
        }
        for (int i = 0; i < offset; i++) {
            sbs[i] = sbs[i] + " ";
        }
        return sbs;
    }

    public String space(int num) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < num; i++) {
            res.append(" ");
        }
        return res.toString();
    }
}
